import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import * as dayjs from 'dayjs';
import { ApiLog } from 'src/database/entities/apiLog';
import { RedisService } from 'src/database/redis';
import { Between } from 'typeorm';
@Injectable()
export class TrackService {
  constructor(private redisService: RedisService) {}
  @Cron('0 0 * * *')
  async syncRedisToMysql() {
    try {
      const value = await this.redisService.redis.get('identify');
      const startDate = dayjs().startOf('day').toDate(); // 获取当前日期的开始时间，即 00:00:00
      const endDate = dayjs().endOf('day').toDate(); // 获取当前日期的结束时间，即 23:59:59
      const event = await ApiLog.findOne({
        where: {
          createdAt: Between(startDate, endDate),
        },
      });
      if (event) {
        event.count = Number(value);
        await ApiLog.save(event);
      } else {
        const log = new ApiLog();
        log.name = 'identify';
        log.count = Number(value);
        await ApiLog.save(log);
      }
      await this.redisService.redis.del('identify');
    } catch (error) {
      console.error('定时任务', error);
    }
  }
}
